package com.cicadamob.contact.api.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Data;
import android.util.Log;

import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Data.SharedPreferencesUtil;
import com.cicadamob.contact.api.Utils.pinyin.PinyinTools;
import com.gmccgz.im.sdk.http.bean.UserCard;
/**
 * 注意：现已将联系人放在自己创建的数据库
 * 该类放弃使用，用APPContactDao类代替
 * @update xmq
 * @date 2016年10月28日
 */
@Deprecated
public class SysContactDao {
	
	private static String[] CONTACT_COLUMNS = {
		//联系人ID
		ContactsContract.Contacts.Data.RAW_CONTACT_ID,
		//联系人显示姓名
		ContactsContract.Contacts.DISPLAY_NAME,
		//事件公历日期
		ContactsContract.CommonDataKinds.Event.START_DATE,
		//事件名称
		ContactsContract.CommonDataKinds.Event.LABEL,
		//事件类型
		ContactsContract.CommonDataKinds.Event.TYPE,
		//帐户名称
		ContactsContract.RawContacts.ACCOUNT_NAME,
		//账户类型
		ContactsContract.RawContacts.ACCOUNT_TYPE,
		//号码
		ContactsContract.CommonDataKinds.Phone.NUMBER
	};
	
	private static final String[] PHONES_PROJECTION = new String[] {  
		Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID,Phone.CONTACT_ID,Phone.RAW_CONTACT_ID,"sort_key",ContactsContract.RawContacts.ACCOUNT_NAME,ContactsContract.RawContacts.ACCOUNT_TYPE};
	
	/**
	 * 根据电话号码查询姓名（在一个电话打过来时，如果此电话在通讯录中，则显示姓名）
	 * 
	 * @param phone
	 */
	public Map<String, Object> ReadNameByPhone(Context mContext,String phone) {
		Map<String, Object> item = new HashMap<String, Object>();
		// uri= content://com.android.contacts/data/phones/filter/#
		Uri uri = Uri
				.parse("content://com.android.contacts/data/phones/filter/"
						+ phone);
		ContentResolver resolver = mContext.getContentResolver();
		Cursor cursor = resolver.query(uri,
				new String[] { Data.CONTACT_ID }, null, null, null); // 从raw_contact表中返回display_name
		if (cursor.moveToFirst()) {
			Log.i("Contacts", "name=" + cursor.getInt(0));
			int id = cursor.getInt(0);
			uri = Uri.parse("content://com.android.contacts/contacts/" + id
					+ "/data"); // 如果要获得data表中某个id对应的数据，则URI为content://com.android.contacts/contacts/#/data
			Cursor cursor2 = resolver.query(uri, new String[] { Data.DATA1,
					Data.MIMETYPE }, null, null, null); // data1存储各个记录的总数据，mimetype存放记录的类型，如电话、email等
			while (cursor2.moveToNext()) {
				String data = cursor2
						.getString(cursor2.getColumnIndex("data1"));
				if (cursor2.getString(cursor2.getColumnIndex("mimetype"))
						.equals("vnd.android.cursor.item/name")) { // 如果是名字
					item.put("name", data);
				} else if (cursor2
						.getString(cursor2.getColumnIndex("mimetype")).equals(
								"vnd.android.cursor.item/phone_v2")) { // 如果是电话
					item.put("phone", data);
				} else if (cursor2
						.getString(cursor2.getColumnIndex("mimetype")).equals(
								"vnd.android.cursor.item/email_v2")) { // 如果是email
					item.put("email", data);
				} else if (cursor2
						.getString(cursor2.getColumnIndex("mimetype")).equals(
								"vnd.android.cursor.item/postal-address_v2")) { // 如果是地址
					item.put("address", data);
				} else if (cursor2
						.getString(cursor2.getColumnIndex("mimetype")).equals(
								"vnd.android.cursor.item/organization")) { // 如果是组织
					item.put("organization", data);
				}
			}
			if (cursor2 != null)
				cursor2.close();
			if (cursor != null)
				cursor.close();
		}
		return item;
	}

	
	/**
	 * 获取所有联系人(安装状态，排序，首字母，全拼，名称，电话号码，id)
	 * @author lvbo
	 * @param mContext
	 * @return
	 * @version 创建时间：2014-2-24 下午4:04:39 
	 */
	public static ArrayList<Contact>  getAllContacts(Context mContext) {
		ContentResolver resolver = mContext.getContentResolver();
		Map<String, String> phones=getInstallPhone(mContext);
		
		Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null,null, " sort_key asc"); // 获得_id属性
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		long lasteContactId=-1;
		boolean isFirst = true;
		Contact item = null;
		List<String> contactPhones = null;
		while (cursor.moveToNext()) {
			String displayName=cursor.getString(cursor.getColumnIndex("display_name"));
			String phoneNumber = cursor.getString(1);
			long contact_id = cursor.getLong(4);// 获得id并且在data中寻找数据
			long contact_id1 = cursor.getLong(3);// 获得id并且在data中寻找数据
			
//			Long photoid = cursor.getLong(2);
			//去空格
			if(phoneNumber.contains(" ")){
				phoneNumber=phoneNumber.replace(" ", "");
			}
			//去横杠
			if(phoneNumber.contains("-")){
				phoneNumber=phoneNumber.replace("-", "");
			}
			//去“+86”前缀
			if(phoneNumber.contains("+86")){
				phoneNumber=phoneNumber.replace("+86", "");
			}
			
			//安装状态
			if (phones.containsKey(phoneNumber)) {
				item.setInstall(1);
			}
			
			if(phoneNumber==null || phoneNumber.length()==0) continue;
			if(lasteContactId!=contact_id){
				if(!isFirst){
					item.setPhoneList(contactPhones);
					contacts.add(item);
				}
				contactPhones = new ArrayList<>();
				item = new Contact();
				
				item.setUserid(""+contact_id);
				item.setDisplayName(displayName);
				item.setLinkPhone(phoneNumber);
				
				if(StringUtil.isEmpty(displayName)){
					item.setLetter("#");
				}else{
					String letter=PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
					char[] firstChar= letter.toCharArray();
					if(firstChar!=null&&firstChar.length>0){
						if(firstChar[0]>='a'&&firstChar[0]<='z'){
							item.setLetter(letter.toUpperCase());
						}else if(firstChar[0]>='A'&&firstChar[0]<='Z'){
							item.setLetter(letter);
						}else{
							item.setLetter("#");
						}
					}
				}
				item.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
				item.setAllPy(PinyinTools.getAllPinYin(displayName));
				item.setSort(PinyinTools.getSort(displayName));
			}
			
			contactPhones.add(phoneNumber);
			isFirst = false;
			lasteContactId=contact_id;
			
//			Log.e("拼音", item.getLetter()+" "+item.getAllPy());
			
//			String sort_key=cursor.getString(cursor.getColumnIndex("sort_key"));
//			//得到联系人头像Bitamp  
//			if(phoneNumber==null || phoneNumber.length()==0) continue;
//			
//			item.setUserid(""+contact_id);
//			item.setDisplayName(displayName);
//			item.setLinkPhone(phoneNumber);
//			
//			char[] firstChar= sort_key.toCharArray();
//			if(firstChar!=null&&firstChar.length>0){
//				int tenChar=firstChar[0];
//				if(tenChar>64&&tenChar<91){
//					item.setLetter(String.valueOf(firstChar[0]));
//				}else if(tenChar>96&&tenChar<123){
//					item.setLetter(String.valueOf(firstChar[0]).toUpperCase());
//				}else{
//					item.setLetter("#");
//				}
//			}
//			
//			if(sort_key!=null && displayName!=null ){
//				if( sort_key.equals(displayName)){
//					//名称全是拼音
//					item.setAllPy(sort_key.trim());
//					String [] s=sort_key.split(" ");
//						String firstPinYin="";
//						for (String first : s) {
//							firstPinYin+=first;
//						}
//						
//						item.setFirstPy(firstPinYin);
//					
//				}else{
//					//名称有中文
//					String [] s=sort_key.split(" ");
//					String py="";
//					String first="";
//					for (int i = 0; i < s.length; i++) {
//						String p = s[i];
//						if(i%2==0){
//							py+=p;
//							if(p.length()>0){
//								first+=p.substring(0, 1);
//							}
//						}
//					}
//					item.setAllPy(py);
//					item.setFirstPy(first);
//					
//				}
//			}
			
		}
		if(item!=null&&contactPhones!=null){
			item.setPhoneList(contactPhones);
			contacts.add(item);
		}
		if (cursor != null)
			cursor.close();
		
		return contacts;
	}

    /**
     * 获取所有联系人(只有电话号码和名称)
     * @author lvbo
     * @param mContext
     * @return
     * @version 创建时间：2014-2-24 下午4:04:39
     */
    public static Contact  getContactByNumbersOrName(Context mContext,String where) {
        ContentResolver resolver = mContext.getContentResolver();

        Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null,null, " sort_key asc"); // 获得_id属性
//		long lasteContactId=-1;
        while (cursor.moveToNext()) {
            String displayName=cursor.getString(cursor.getColumnIndex("display_name"));
            String phoneNumber = cursor.getString(1);
            long contact_id = cursor.getLong(3);// 获得id并且在data中寻找数据

//			if(lasteContactId==contact_id)
//				continue;
//			else
//				lasteContactId=contact_id;
            //去空格
            if(phoneNumber.contains(" ")){
                phoneNumber=phoneNumber.replace(" ", "");
            }
            //去横杠
            if(phoneNumber.contains("-")){
                phoneNumber=phoneNumber.replace("-", "");
            }
            //去“+86”前缀
            if(phoneNumber.contains("+86")){
                phoneNumber=phoneNumber.replace("+86", "");
            }


//			if(phoneNumber==null || phoneNumber.length()==0) continue;
            if(phoneNumber.equals(where) || displayName.equals(where)){
                Contact item = new Contact();
                item.setUserid(""+contact_id);
                item.setDisplayName(displayName);
                item.setLinkPhone(phoneNumber);
                return item;
            }


        }
        if (cursor != null)
            cursor.close();

        return null;
    }
	/**
	 * 获取所有联系人,可以显示重复联系人(只有电话号码和名称)
	 * @author lvbo
	 * @param mContext
	 * @return
	 * @version 创建时间：2014-2-24 下午4:04:39 
	 */
	public static ArrayList<Contact>  getContacts(Context mContext) {
		ContentResolver resolver = mContext.getContentResolver();
		
		Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null,null, " sort_key asc"); // 获得_id属性
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		while (cursor.moveToNext()) {
			String displayName=cursor.getString(cursor.getColumnIndex("display_name"));
			String phoneNumber = cursor.getString(1);
			long contact_id = cursor.getLong(3);// 获得id并且在data中寻找数据
			Contact item = new Contact();
			//去空格
			if(phoneNumber.contains(" ")){
				phoneNumber=phoneNumber.replace(" ", "");
			}
			//去横杠
			if(phoneNumber.contains("-")){
				phoneNumber=phoneNumber.replace("-", "");
			}
			//去“+86”前缀
			if(phoneNumber.contains("+86")){
				phoneNumber=phoneNumber.replace("+86", "");
			}
			
			
			if(phoneNumber==null || phoneNumber.length()==0) continue;
			
			item.setUserid(""+contact_id);
            item.setDisplayName(displayName);
            item.setLinkPhone(phoneNumber);
			item.setAllPy(PinyinTools.getAllPinYin(displayName));
			contacts.add(item);
		}
		if (cursor != null)
			cursor.close();
		
		return contacts;
	}
	
	
	
	/**
	 * 获取没有安装客户端的联系人,用于从服务端获取安装状态
	 * @author lvbo
	 * @param mContext
	 * @return
	 * @version 创建时间：2014-2-24 下午4:04:39 
	 */
	public static Map<String, String>  getUnInstallContacts(Context mContext) {
		ContentResolver resolver = mContext.getContentResolver();
		Map<String, String> phones=getInstallPhone(mContext);
		
		Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null,null, " sort_key asc"); // 获得_id属性
		Map<String, String> contacts = new LinkedHashMap<String, String>();
		long lasteContactId=-1;
		while (cursor.moveToNext()) {
			String displayName=cursor.getString(cursor.getColumnIndex("display_name"));
			String phoneNumber = cursor.getString(1);
			long contact_id = cursor.getLong(3);// 获得id并且在data中寻找数据
			if(lasteContactId==contact_id)
				continue;
			else
				lasteContactId=contact_id;
			
			//去空格
			if(phoneNumber.contains(" ")){
				phoneNumber=phoneNumber.replace(" ", "");
			}
			//去横杠
			if(phoneNumber.contains("-")){
				phoneNumber=phoneNumber.replace("-", "");
			}
			//去“+86”前缀
			if(phoneNumber.contains("+86")){
				phoneNumber=phoneNumber.replace("+86", "");
			}
			//非手机号码不添加
			if(!ValidUtil.isValidMobilePhoneNumber(phoneNumber)) continue;
			
			if(phones!=null&&phones.size()>0){
				for (String p : phones.keySet()) {
					if(phoneNumber.equals(p)){
					continue;
					}else{
						contacts.put(phoneNumber, displayName);
					}
				}
			}else{
				contacts.put(phoneNumber,displayName);
			}
		}
		if (cursor != null)
			cursor.close();
		
		return contacts;
	}
	
	
	/**
	 * 搜索本地联系人
	 * @author lvbo
	 * @param mContext
	 * @return
	 * @version 创建时间：2014-2-24 下午4:04:39 
	 */
	public static ArrayList<Contact>  getContactsByWhere(Context mContext,String  txt) {
		ContentResolver resolver = mContext.getContentResolver();
		Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null,	null, " sort_key asc"); // 获得_id属性
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		long lasteContactId=-1;
		Map<String, String> phones=getInstallPhone(mContext);
		while (cursor.moveToNext()) {
//			boolean isAdd=true;
			Contact item = new Contact();
			long contact_id = cursor.getLong(3);// 获得id并且在data中寻找数据
			if(lasteContactId==contact_id)
				continue;
			else
				lasteContactId=contact_id;
			Long photoid = cursor.getLong(2);  
			
			String sort_key=cursor.getString(cursor.getColumnIndex("sort_key"));
			String displayName=cursor.getString(cursor.getColumnIndex("display_name"));
			String phoneNumber = cursor.getString(1);
			displayName=displayName==null?phoneNumber:displayName;//如果名称为空就显示电话号码
			//得到联系人头像Bitamp  
		    Bitmap contactPhoto = null;  
			if(phoneNumber==null || phoneNumber.length()==0) continue;
			
			
			
//			item.setContactPhoto(contactPhoto);
			
			//去空格
			if(phoneNumber.contains(" ")){
				phoneNumber=phoneNumber.replace(" ", "");
			}
			//去横杠
			if(phoneNumber.contains("-")){
				phoneNumber=phoneNumber.replace("-", "");
			}
			//去“+86”前缀
			if(phoneNumber.contains("+86")){
				phoneNumber=phoneNumber.replace("+86", "");
			}
			
			for (String p : phones.keySet()) {
				if(phoneNumber.equals(p)){
					item.setInstall(1);
					break;
				}
			}
			
			item.setUserid(""+contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);
			item.setSourceId("1");
			
			if(phoneNumber==null || phoneNumber.length()==0) continue;
			
			item.setUserid(""+contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);
			
			String  letter=PinyinTools.getShouPinYin(displayName.substring(0,1));
			char[] letterChar=letter.toCharArray();
			if(letterChar!=null&&letterChar.length>0){
				int tenChar=letterChar[0];
				if(tenChar>'a'&&tenChar<'z'){
					item.setLetter(letter.toUpperCase());
				}else if(tenChar>'A'&&tenChar<'Z'){
					item.setLetter(letter);
				}else{
					item.setFirstPy("#");
				}
			}
			
			item.setAllPy(PinyinTools.getAllPinYin(displayName));
			item.setSort(PinyinTools.getSort(displayName));
			
			contacts.add(item);
		}
		if (cursor != null)
			cursor.close();
		
		
		ArrayList<Contact> searcherContacts = new ArrayList<Contact>();
		String keyEncode = "";
		if (!StringUtil.isEmpty(txt)) {
			keyEncode = StringUtil.encode(txt);
			if (StringUtil.isNum(txt)) {
				// 数字
				for (Contact contact : contacts) {
					if (contact.getLinkPhone().contains(txt)) {
						searcherContacts.add(contact);
					}
				}
			} else if (keyEncode.length() == txt.length()) {
				// 拼音
				String txtTmp = txt.toUpperCase();
				for (Contact contact : contacts) {
					if (contact.getAllPy().contains(txtTmp)) {
						searcherContacts.add(contact);
					} else if (contact.getFirstPy()!=null && contact.getFirstPy().contains(txtTmp)) {
						searcherContacts.add(contact);
					}else if (contact.getDisplayName()!=null && contact.getDisplayName().contains(txt)) {
						searcherContacts.add(contact);
					}
				}
			} else {
				// 名称
				for (Contact contact : contacts) {
					if (contact.getDisplayName().replace(" ", "").contains(txt)) {
						searcherContacts.add(contact);
					}
				}
			}
		}
		
		return searcherContacts;
	}
	
	
	
	/**根据联系人id删除联系人
	 * @param mContext
	 * @param id
	 */
	public static void DeleteContacts(Context mContext,String id){
		// 根据姓名求id
		Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
		ContentResolver resolver = mContext.getContentResolver();
		// 根据id删除data中的相应数据
		ContentValues cv=new ContentValues();
		cv.put(Phone.CONTACT_ID, Long.valueOf(id));
//		resolver.update(uri,cv, Phone.CONTACT_ID + "=?",new String[] { id });
//	    uri = Uri.parse("content://com.android.contacts/data");
//		resolver.delete(Phone.CONTENT_URI, Data._ID + "=?", new String[] { id });
		 uri = Uri.parse("content://com.android.contacts/data");  
		 resolver.delete(uri, Data.RAW_CONTACT_ID + "=?", new String[] { id });
		 uri = Uri.parse("content://com.android.contacts/raw_contacts");
		 resolver.delete(uri, Phone.CONTACT_ID + "=?", new String[] { id });
//		 uri = Uri.parse("content://com.android.contacts/contacts");
//		 resolver.delete(uri, Phone.CONTACT_ID + "=?", new String[] { id });
	}
	
	/**
	 * 
	 * 根据名称查询
	 * @author ym
	 * @param mContext
	 * @param txt
	 * @return
	 * @version 创建时间：2014-3-26 下午7:20:52
	 */
	public static ArrayList<Contact>  getContactsByName(Context mContext,String name,int start,int count) {
		ContentResolver resolver = mContext.getContentResolver();
		Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, "display_name like '%"+name+"%'", null, " sort_key asc limit " + start +", " + count); // 获得_id属性
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		while(cursor.moveToNext()){
			Contact cc = new Contact();
			cc.setDisplayName(cursor.getString(cursor.getColumnIndex("display_name")));
			cc.setLinkPhone(cursor.getString(1));
			cc.setSourceId("1");
			contacts.add(cc);
		}
		return contacts;
	}

	
	
	
	
	/**获取所有安装客户端的联系人
	 * @param mContext
	 * @return
	 */
	public static Map<String, String> getInstallPhone(Context mContext){
		Map<String, String> installPhone=new HashMap<String,String>();
		SQLiteDatabase db=DBManager.getInstance(mContext).openDatabase();
		Cursor cursor=db.rawQuery(" select * from install_table", null);
		while (cursor.moveToNext()) {
			String phone=cursor.getString(cursor.getColumnIndex("install_phone"));
			String name=cursor.getString(cursor.getColumnIndex("p_name"));
			installPhone.put(phone,name);
		}
		if(cursor!=null) cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return installPhone;
	}
	
	/**
	 * 搜索已经安装客户端的用户
	 * @param mContext
	 * @param phones
	 * @param contact
	 */
	public static Map<String, String> getInstallPhoneByName(Context mContext,String keywrod){
		Map<String, String> installPhone=new HashMap<String,String>();
		SQLiteDatabase db=DBManager.getInstance(mContext).openDatabase();
		Cursor cursor=db.rawQuery(" select * from install_table where p_name like '%" + keywrod + "%'", null);
		while (cursor.moveToNext()) {
			String phone=cursor.getString(cursor.getColumnIndex("install_phone"));
			String name=cursor.getString(cursor.getColumnIndex("p_name"));
			installPhone.put(phone,name);
		}
		if(cursor!=null) cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return installPhone;
	}
	
	/**添加安装客户端用户
	 * @param mContext
	 * @param phones
	 * @param contact
	 */
	public static void addInstallPhone(Context mContext,ArrayList<String> phones,Map<String, String> contact){
		SQLiteDatabase db=DBManager.getInstance(mContext).openDatabase();
//		db.execSQL("delete from install_table");//添加前把表的内容删除
		for(String p:phones){
			db.execSQL("insert into install_table ( install_phone ,p_name) values ('"+p+"','" + contact.get(p) + "')");
		}
		DBManager.getInstance(mContext).closeDatabase();
		
	}
	
	
	/**从服务端获取本地联系人还有哪些人已经安装客户端
	 * @param mContext
	 */
	public static boolean getUnInstallStatusOfContact(final Context mContext){
		long lastedtime=SharedPreferencesUtil.getLong(mContext,"getinstallStatus");
		long nowTime=new Date().getTime();
		if(lastedtime!=-1 && (nowTime-lastedtime)<86400000){
			return true;
		}
		 Map<String, String> sContacts = getUnInstallContacts(mContext);
		 LoadUnInstall loader=new LoadUnInstall(mContext, null, sContacts);
		if( loader.loadInstall()){
			SharedPreferencesUtil.putLong(mContext, "getinstallStatus", nowTime);
			 //获取这些未安装的安装状态
			return true;
		}
		 return false;
	}
	
	/***获取所有联系人，返回json字符串*/
	public static  ArrayList<UserCard> getAllRecords(Context mContext) {
		ArrayList<Contact> result=null;
		result=getAllContacts(mContext);
		ArrayList<UserCard> users=new ArrayList<>();
		
		for (Contact contact : result) {
			UserCard item=new UserCard();
			item.setMoblie(contact.getLinkPhone());
			item.setName(contact.getDisplayName());
			users.add(item);
		}
	 
	  return users;
	}
	
	/**
	 * 获得联系人的key:电话，value:姓名 的Map(同一个联系人下多个号码情况，只使用第一个号码)
	 * @param context
	 * @return
	 */
	public static Map<String,String> getContactPhoneNameMap(Context context){
		Map<String,String> map=new HashMap<String, String>();
		Cursor cursor=null;
		try {
			cursor = context.getContentResolver().query(Phone.CONTENT_URI, PHONES_PROJECTION, null,null, " sort_key asc"); 
			long lasteContactId=-1;
			if(cursor!=null && cursor.getCount()>0){
				while (cursor.moveToNext()) {
					String displayName=cursor.getString(cursor.getColumnIndex("display_name"));
					String phoneNumber = cursor.getString(1);
					long contact_id = cursor.getLong(3);// 获得id并且在data中寻找数据
					if(lasteContactId==contact_id)
						continue;
					else
						lasteContactId=contact_id;
					
					//去空格
					if(phoneNumber.contains(" ")){
						phoneNumber=phoneNumber.replace(" ", "");
					}
					//去横杠
					if(phoneNumber.contains("-")){
						phoneNumber=phoneNumber.replace("-", "");
					}
					//去“+86”前缀
					if(phoneNumber.contains("+86")){
						phoneNumber=phoneNumber.replace("+86", "");
					}
					
					if(StringUtil.isEmpty(displayName)){
						displayName=phoneNumber;
					}
					
					map.put(phoneNumber, displayName);
					
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(cursor!=null){
				cursor.close();
			}
			
		}
		return map;
		
	}
	
	/**
	 * 该方法获得某个系统联系人下面的所有号码。但是有bug...会少第一个号码...
	 * 建议使用下面方法getSystemContactPhones
	 * 2016年10月27日
	 * @param mContext
	 * @param userId
	 * @return
	 */
	public static List<String> getPhones(Context mContext, String userId) {
		List<String> phones = new LinkedList<>();
		Cursor phoneCursor = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + userId, null, null);
		if (phoneCursor.moveToFirst()) {
			while (phoneCursor.moveToNext()) {
				// 遍历所有的联系人下面所有的电话号码
				String phoneNumber = phoneCursor.getString(phoneCursor
						.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				if (phoneNumber.contains(" ")) {
					phoneNumber = phoneNumber.replace(" ", "");
				}
				// 去横杠
				if (phoneNumber.contains("-")) {
					phoneNumber = phoneNumber.replace("-", "");
				}
				// 去“+86”前缀
				if (phoneNumber.contains("+86")) {
					phoneNumber = phoneNumber.replace("+86", "");
				}
				phones.add(phoneNumber);
			}
		}
		return phones;
	}

	/**
	 * 该方法获得某个系统联系人下面的所有号码
	 * @param mContext
	 * @param userId
	 * @return
	 */
	public static List<String> getSystemContactPhones(Context mContext, String userId) {
		List<String> phones = new LinkedList<>();
		Cursor phoneCursor = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + userId, null, null);
		while (phoneCursor.moveToNext()) {
			// 遍历所有的联系人下面所有的电话号码
			String phoneNumber = phoneCursor.getString(phoneCursor
					.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			phones.add(phoneNumber);
		}
		if (phoneCursor != null) {
			phoneCursor.close();
		}
		return phones;
	}
	
}
